<template>
  <div class="system-logs">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>系统日志</span>
          <div class="header-actions">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索日志内容"
              style="width: 200px; margin-right: 10px;"
              clearable
            />
            <el-select 
              v-model="searchForm.level" 
              placeholder="日志级别" 
              style="width: 120px; margin-right: 10px;"
              clearable
            >
              <el-option label="错误" value="error" />
              <el-option label="警告" value="warn" />
              <el-option label="信息" value="info" />
              <el-option label="调试" value="debug" />
            </el-select>
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="margin-right: 10px;"
            />
            <el-button type="primary" @click="searchLogs">搜索</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="logList" v-loading="loading" stripe>
        <el-table-column prop="timestamp" label="时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.timestamp) }}
          </template>
        </el-table-column>
        <el-table-column prop="level" label="级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getLevelType(row.level)">
              {{ getLevelText(row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="module" label="模块" width="120" />
        <el-table-column prop="message" label="消息" />
        <el-table-column prop="ip" label="IP地址" width="150" />
        <el-table-column prop="user" label="操作用户" width="120" />
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button size="small" @click="viewLogDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 日志详情对话框 -->
    <el-dialog title="日志详情" v-model="detailDialogVisible" width="600px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="时间">{{ formatDate(currentLog.timestamp) }}</el-descriptions-item>
        <el-descriptions-item label="级别">
          <el-tag :type="getLevelType(currentLog.level)">
            {{ getLevelText(currentLog.level) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="模块">{{ currentLog.module }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ currentLog.ip }}</el-descriptions-item>
        <el-descriptions-item label="操作用户">{{ currentLog.user }}</el-descriptions-item>
        <el-descriptions-item label="消息">{{ currentLog.message }}</el-descriptions-item>
        <el-descriptions-item label="详细信息">
          <pre>{{ currentLog.details }}</pre>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getSystemLogs } from '@/api/system'
import { formatDate } from '@/utils/format'

interface Log {
  id: number
  timestamp: string
  level: string
  module: string
  message: string
  ip: string
  user: string
  details: string
}

const loading = ref(false)
const logList = ref<Log[]>([])
const detailDialogVisible = ref(false)
const currentLog = ref<Log>({
  id: 0,
  timestamp: '',
  level: '',
  module: '',
  message: '',
  ip: '',
  user: '',
  details: ''
})
const dateRange = ref<[Date, Date] | null>(null)

const searchForm = reactive({
  keyword: '',
  level: ''
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const loadSystemLogs = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword,
      level: searchForm.level,
      startTime: dateRange.value?.[0] ? dateRange.value[0].toISOString() : undefined,
      endTime: dateRange.value?.[1] ? dateRange.value[1].toISOString() : undefined
    }
    const response = await getSystemLogs(params)
    logList.value = response.data.records
    pagination.total = response.data.total
  } catch (error) {
    ElMessage.error('获取系统日志失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const searchLogs = () => {
  pagination.currentPage = 1
  loadSystemLogs()
}

const getLevelType = (level: string) => {
  switch (level.toLowerCase()) {
    case 'error': return 'danger'
    case 'warn': return 'warning'
    case 'info': return 'primary'
    case 'debug': return 'success'
    default: return 'info'
  }
}

const getLevelText = (level: string) => {
  switch (level.toLowerCase()) {
    case 'error': return '错误'
    case 'warn': return '警告'
    case 'info': return '信息'
    case 'debug': return '调试'
    default: return level
  }
}

const viewLogDetail = (log: Log) => {
  currentLog.value = log
  detailDialogVisible.value = true
}

const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadSystemLogs()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  loadSystemLogs()
}

onMounted(() => {
  loadSystemLogs()
})
</script>

<style scoped lang="scss">
.system-logs {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  pre {
    white-space: pre-wrap;
    word-wrap: break-word;
    margin: 0;
  }
}
</style>